﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExcelUtilities.Cfg
{
    /// <summary>
    /// 单元格位置
    /// </summary>
    public struct CellPosition
    { 
        /// <summary>
        /// 行（从1开始）
        /// </summary>
        public int Row;
        /// <summary>
        /// 列（从1开始）
        /// </summary>
        public int Col;
    }
    
    /// <summary>
    /// 单元格位置转换
    /// 行列和地址转换
    /// </summary>
    public static class AddressExtensions
    {
        const string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string Digits = "123456789";

        /// <summary>
        /// 将单元格地址转换成行列
        /// </summary>
        /// <param name="address">单元格地址</param>
        /// <returns>单元格行列</returns>
        public static CellPosition ToPos(this string address)
        {
            CellPosition pos = new CellPosition();
            address = address.Trim().ToUpper();
            string colAddr = address.TrimEnd(Digits.ToCharArray());
            string rowAddr = address.TrimStart(Letters.ToCharArray());
            for (int i = 0; i < colAddr.Length; i++)
            {
                pos.Col += ((int)colAddr[colAddr.Length - i - 1] - 64) * (int)Math.Pow(26, i);
            }
            if (!string.IsNullOrEmpty(rowAddr))
                pos.Row = int.Parse(rowAddr);

            return pos;
        }

        /// <summary>
        /// 将行列信息转成单元格地址
        /// </summary>
        /// <param name="postion">单元格行列</param>
        /// <returns></returns>
        public static string ToAddr(this CellPosition postion)
        {
            StringBuilder address = new StringBuilder();
            if (postion.Col > 26)
                address.Append((char)(postion.Col / 26 + 64));
            address.Append((char)(postion.Col % 26 + 64));
            address.Append(postion.Row.ToString());

            return address.ToString();
        }

        /// <summary>
        /// 将单元格列转成地址
        /// </summary>
        /// <param name="col">单元格列</param>
        /// <returns>返回列名</returns>
        public static string ToAddr(this int col)
        {
            StringBuilder address = new StringBuilder();
            if (col > 26)
                address.Append((char)(col / 26 + 64));
            address.Append((char)(col % 26 + 64));
            return address.ToString();
        }
    }
}